package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingDao;
import com.itheima.entity.Result;
import com.itheima.pojo.*;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 体检预约服务
 */
@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    @Autowired
    private MemberDao memberDao;

    @Autowired
    private OrderDao orderDao;

    //体检预约
    public Result order(Map map) throws Exception {

        //1.检查当前日期是否进行了预约设置
        String orderDate = (String) map.get("orderDate");
        Date date = DateUtils.parseString2Date(orderDate);
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(date);
        if(orderSetting == null){
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }

        //2.检查预约日期是否预约已满
        int number = orderSetting.getNumber();//可预约人数
        int reservations = orderSetting.getReservations();//已预约人数
        if(reservations >= number){
            //预约已满，不能预约
            return new Result(false,MessageConstant.ORDER_FULL);
        }

        //检查当前用户是否为会员，根据手机号判断
        String telephone = (String) map.get("telephone");
        Member member = memberDao.findByTelephone(telephone);

        //3.防止重复预约
        if(member != null){
            Integer memberId = member.getId();
            int setmealId = Integer.parseInt((String)map.get("setmealId"));
            Order order = new Order(memberId, date, null, null, setmealId);
            List<Order> list = orderDao.findByCondition(order);
            if(list != null && list.size() > 0){
                //已经完成了预约，不能重复预约
                return new Result(false,MessageConstant.HAS_ORDERED);
            }
        }
        //可以预约，设置预约人数加一
        orderSetting.setReservations(orderSetting.getReservations()+1);
        orderSettingDao.editReservationsByOrderDate(orderSetting);

        // 4.检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
        if(member == null){
            //当前用户不是会员，需要添加到会员表
            member = new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber(telephone);
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRegTime(new Date());
            memberDao.add(member);
        }

        //5.保存预约信息到预约表
        Order order = new Order(member.getId(), date, (String)map.get("orderType"), Order.ORDERSTATUS_NO,
                Integer.parseInt((String)map.get("setmealId")));
        orderDao.add(order);
        return new Result(true, MessageConstant.ORDER_SUCCESS, order.getId());

    }

    //根据id查询预约信息，包括体检人信息、套餐信息
    public Map findById(Integer id) throws Exception {
        Map map = orderDao.findById4Detail(id);
        if(map != null){
            //处理日期格式
            Date orderDate = (Date) map.get("orderDate");
            map.put("orderDate", DateUtils.parseDate2String(orderDate));
        }
        return map;
    }
    //体检预约
    public Result add(Map map) throws Exception {
        String orderDate = (String) map.get("orderDate");
        //1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(DateUtils.parseString2Date(orderDate));
        if (orderSetting == null) {
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
        int number = orderSetting.getNumber();
        int reservations = orderSetting.getReservations();
        if (reservations >= number) {
            return new Result(false, MessageConstant.ORDER_FULL);
        }

        //3、检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约 则无法完成再次预约
        //查询当前手机号所对应的会员信息,根据会员信息查出所预约的套餐
        String telephone = map.get("telephone").toString();
        Member member = memberDao.findByTelephone(telephone);
        if (member != null) {
            //判断是否有重复预约(依据会员id,预约日期,预约的套餐id)
            Integer memberId = member.getId();
            Integer setmealId = Integer.parseInt(map.get("setmealId").toString());
            Order order = new Order();
            order.setMemberId(memberId);
            order.setOrderDate(DateUtils.parseString2Date(orderDate));
            order.setSetmealId(setmealId);

            List<Order> orderList = orderDao.findByCondition(order);
            if (orderList != null && orderList.size() > 0) {
                //说明已存在预约,不能重复添加
                return new Result(false, MessageConstant.HAS_ORDERED);
            }
        } else {
            //4、检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
            member = new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber(telephone);
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRegTime(new Date());
            memberDao.add(member);//自动完成会员注册
        }


        //5、预约成功，更新当日的已预约人数
        Order order = new Order();
        order.setMemberId(member.getId());
        order.setOrderDate(DateUtils.parseString2Date(orderDate));
        order.setSetmealId(Integer.parseInt(map.get("setmealId").toString()));
        //       order.setOrderType(map.get("orderType").toString());
        order.setOrderStatus(Order.ORDERSTATUS_NO);//到诊状态

        orderDao.add(order);

        orderSetting.setReservations(orderSetting.getReservations() + 1);
        orderSettingDao.editReservationsByOrderDate(orderSetting);
        return new Result(true, MessageConstant.ORDERSETTING_SUCCESS, order.getId());
    }

    @Override
    public List<Setmeal> findSetmealIdByOrderId(int id) {
        return orderDao.findSetmealIdByOrderId(id);
    }

    @Override
    public void edit(Map map, Integer setmealId) {
        Integer id = (Integer) map.get("id");
        Integer orderIdByMemberId = orderDao.findOrderIdByMemberId(id);
        Member member = new Member();
        String memberName = (String) map.get("memberName");
        map.put("setmealId",setmealId);
        member.setId(orderIdByMemberId);
        member.setName(memberName);
        memberDao.edit(member);
        // memberDao.SetName(MemberId,memberName);
        orderDao.edit(map);
    }

    @Override
    public void delete(Integer id) {

        //根据id找出预约日期
        Date orderDateById = orderDao.findOrderDateById(id);
        //再根据预约日期拿到ordersetting对象
        OrderSetting setting = orderSettingDao.findByOrderDate(orderDateById);
        //将已预约人数-1
        setting.setReservations(setting.getReservations()-1);
        orderSettingDao.editReservationsByOrderDate(setting);

        orderDao.delete(id);

    }

    @Override
    public void  changeStatus(Map map) {
        orderDao.edit(map);

    }
    //根据id查询预约信息，包括体检人信息、套餐信息
    public Map findOrderById(Integer id) throws Exception {
        Map map = orderDao.findById5Detail(id);
        if (map != null) {
            //处理日期格式
            Date orderDate = (Date) map.get("orderDate");
            map.put("orderDate", DateUtils.parseDate2String(orderDate));
        }
        return map;
    }

    //分页查询
    public PageInfo<OrderManage> findPage(Map map) {
        Integer currentPage = (Integer) map.get("currentPage");
        String endDate = (String) map.get("endDate");
        String orderStatus = (String) map.get("orderStatus");
        String orderType = (String) map.get("orderType");
        Integer pageSize = (Integer) map.get("pageSize");
        String queryString = (String) map.get("queryString");
        String startDate = (String) map.get("startDate");

        PageHelper.startPage(currentPage, pageSize);
        List<OrderManage> list = orderDao.findByString(map);
        PageInfo<OrderManage> pageInfo = new PageInfo<>(list);

        return pageInfo;

    }
}
